package com.juyu.miliao.api.util;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Md5Util {
	/***
	 * MD5加密 生成32位md5码
	 * 
	 * @param 待加密字符串
	 * @return 返回32位md5码
	 */
	public static String md5Encode(String inStr) {
		try {
			MessageDigest md5 = null;

			md5 = MessageDigest.getInstance("MD5");

			byte[] byteArray = inStr.getBytes("UTF-8");
			byte[] md5Bytes = md5.digest(byteArray);
			StringBuffer hexValue = new StringBuffer();
			for (int i = 0; i < md5Bytes.length; i++) {
				int val = ((int) md5Bytes[i]) & 0xff;
				if (val < 16) {
					hexValue.append("0");
				}
				hexValue.append(Integer.toHexString(val));
			}
			return hexValue.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

	}

	/**
	 * 官方微信支付签名
	 * 
	 * @param dataMap
	 * @param securityKey
	 * @return
	 */
	public static String signGFWXPayDataMD5(Map<String, String> dataMap, String securityKey) {
		if (dataMap == null) {
			return null;
		}
		Set<String> keySet = dataMap.keySet();
		List<String> keyList = new ArrayList<String>(keySet);
		Collections.sort(keyList);

		StringBuilder toMD5StringBuilder = new StringBuilder();
		for (String key : keyList) {
			String value = dataMap.get(key);

			if (value != null && value.length() > 0) {
				toMD5StringBuilder.append(key + "=" + value + "&");
			}
		}
		toMD5StringBuilder.append("key=" + securityKey);
		String lastMD5Result = md5Encode(toMD5StringBuilder.toString()).toUpperCase();
		return lastMD5Result;
	}

}
